// 解析json为字段
import {
  checkboxConfig,
  dateConfig,
  inputConfig,
  numberConfig,
  radioConfig,
  selectConfig
} from "@/views/formgen/components/GenerateForm/config";
import { toLower } from "lodash-es";

/**
 * 测试数据
 * [
 *     {
 *         "type": "单行文本",
 *         "title": "您的姓名？"
 *     },
 *     {
 *         "type": "日期",
 *         "title": "您用餐的日期？"
 *     },
 *     {
 *         "type": "数字",
 *         "title": "您用餐的人数？"
 *     },
 *     {
 *         "type": "单选",
 *         "title": "您对食堂的总体满意度如何？",
 *         "options": [
 *             "非常满意",
 *             "满意",
 *             "一般",
 *             "不满意",
 *             "非常不满意"
 *         ]
 *     },
 *     {
 *         "type": "多选",
 *         "title": "您对食堂的哪些方面感到满意？",
 *         "options": [
 *             "菜品种类",
 *             "菜品味道",
 *             "服务态度",
 *             "环境卫生",
 *             "价格合理"
 *         ]
 *     },
 *     {
 *         "type": "下拉",
 *         "title": "您最喜欢的菜品是什么？",
 *         "options": [
 *             "红烧肉",
 *             "宫保鸡丁",
 *             "水煮鱼",
 *             "酸菜鱼",
 *             "西红柿炒鸡蛋"
 *         ]
 *     }
 * ]
 * @param json
 */
const filedTypeMap: any = {
  单行文本: inputConfig,
  日期: dateConfig,
  数字: numberConfig,
  单选: radioConfig,
  多选: checkboxConfig,
  下拉: selectConfig
};

export const parseJsonToFields = (json: string) => {
  const jsonArr = JSON.parse(json);
  const time = new Date().getTime();
  const formInfo = {
    title: "",
    description: ""
  };
  // 转换成表单数据
  const fields = jsonArr
    .map((item: any, index: number) => {
      if (item.type == "问卷标题") {
        formInfo.title = item.title;
        return null;
      } else if (item.type == "问卷描述") {
        formInfo.description = item.title;
        return null;
      } else {
        const field = JSON.parse(JSON.stringify(filedTypeMap[item.type]));
        if (field) {
          field.config.label = item.title;
        }
        if (field.config.options) {
          field.config.options = item.options.map((op: string, index: string) => {
            return {
              type: op == "其他" ? "input" : "option",
              label: op,
              value: index + 1
            };
          });
        }
        // 找到题目数据定义
        field.config.formId = `${toLower(field.typeId)}${+time + index}`;
        field.vModel = field.config.formId;
        return field;
      }
    })
    .filter((item: any) => item);
  return {
    fields,
    formInfo
  };
};
